import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:rabbit_mobile/service/home.api.dart';

class RegisterIn extends StatefulWidget {
  final String phoneNumber;
  final String code;
  const RegisterIn({super.key, required this.code, required this.phoneNumber});

  @override
  State<RegisterIn> createState() => _RegisterInState();
}

class _RegisterInState extends State<RegisterIn> {
  /// 輸入框控制器
  late TextEditingController? _userNameTextEditingController;

  /// 密碼控制器
  late TextEditingController? _passwordTextEditingController;

  /// 焦點控制器
  late FocusNode? _userNamefocusNode;
  late FocusNode? _passwordfocusNode;

  /// 密碼是否可見
  bool obscureTextToggle = true;

  @override
  void initState() {
    super.initState();
    _userNameTextEditingController = TextEditingController();
    _passwordTextEditingController = TextEditingController();
    _userNamefocusNode = FocusNode();
    _passwordfocusNode = FocusNode();
  }

  @override
  void dispose() {
    super.dispose();
    _userNameTextEditingController!.dispose();
    _passwordTextEditingController!.dispose();
    _userNamefocusNode!.dispose();
    _passwordfocusNode!.dispose();
  }

  void _handleRegister() async {
    if (_userNameTextEditingController!.text.isEmpty || _passwordTextEditingController!.text.isEmpty) {
      EasyLoading.showError('用戶名或密碼不能爲空');
      return;
    }
    // 正側校驗
    RegExp userNameAndPasswordRegExp = RegExp(r'^[0-9a-zA-Z]{5,20}$');
    bool isMatchUserName = userNameAndPasswordRegExp.hasMatch(_userNameTextEditingController!.text);
    bool isMatchPassword = userNameAndPasswordRegExp.hasMatch(_passwordTextEditingController!.text);
    if (!isMatchUserName) {
      EasyLoading.showError("用戶名格式不正確");
      return;
    } else if (!isMatchPassword) {
      EasyLoading.showError('密碼格式不爭確');
      return;
    }
    try {
      final register = await RegisterApi.registerFetch(
        widget.phoneNumber,
        widget.code,
        _passwordTextEditingController!.text,
        _userNameTextEditingController!.text,
      );
      Beamer.of(context).beamToNamed('/login');
    } catch (e) {
      debugPrint('$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: const Color(0xFF00CEA8),
        title: const Text(
          "用戶注冊",
          style: TextStyle(
            fontSize: 14,
            color: Color.fromARGB(255, 255, 255, 255),
          ),
        ),
        leading: IconButton(
          onPressed: () {
            Beamer.of(context).beamBack();
          },
          icon: Image.asset('assets/fanhui_light.png'),
        ),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              padding: const EdgeInsets.only(top: 48, bottom: 48),
              alignment: Alignment.center,
              child: const Text(
                "請填寫賬號密碼",
                style: TextStyle(fontSize: 16, color: Colors.black),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Container(
                alignment: Alignment.center,
                width: double.infinity,
                height: 48,
                decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1, color: Colors.grey.shade300))),
                child: Row(
                  children: [
                    const Padding(
                      padding: EdgeInsets.only(right: 12),
                      child: Text(
                        "用戶名",
                        style: TextStyle(fontSize: 14, color: Colors.black),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: TextField(
                        focusNode: _userNamefocusNode,
                        controller: _userNameTextEditingController,
                        decoration: InputDecoration(
                          hintText: "請輸入手機號碼",
                          border: InputBorder.none,
                          hintStyle: const TextStyle(fontSize: 12, color: Colors.grey),
                          suffixIcon: _userNameTextEditingController!.text.isNotEmpty
                              ? IconButton(
                                  hoverColor: Colors.transparent,
                                  focusColor: Colors.transparent,
                                  splashColor: Colors.transparent,
                                  highlightColor: Colors.transparent,
                                  icon: const Icon(Icons.close),
                                  onPressed: () {
                                    _userNameTextEditingController!.clear();
                                  },
                                )
                              : null,
                        ),
                        cursorColor: const Color(0xFF00CEA8),
                        style: const TextStyle(fontSize: 12, color: Colors.black),
                        keyboardType: TextInputType.number,
                        onChanged: (value) => setState(() {}),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24),
              child: Container(
                alignment: Alignment.center,
                width: double.infinity,
                height: 48,
                decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1, color: Colors.grey.shade300))),
                child: Row(
                  children: [
                    const Padding(
                      padding: EdgeInsets.only(right: 12),
                      child: Text(
                        "密碼",
                        style: TextStyle(fontSize: 14, color: Colors.black),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: TextField(
                        focusNode: _passwordfocusNode,
                        controller: _passwordTextEditingController,
                        decoration: InputDecoration(
                          hintText: "請輸入手機號碼",
                          border: InputBorder.none,
                          hintStyle: const TextStyle(fontSize: 12, color: Colors.grey),
                          suffixIcon: _passwordTextEditingController!.text.isNotEmpty
                              ? IconButton(
                                  hoverColor: Colors.transparent,
                                  focusColor: Colors.transparent,
                                  splashColor: Colors.transparent,
                                  highlightColor: Colors.transparent,
                                  icon: const Icon(Icons.close),
                                  onPressed: () {
                                    _userNameTextEditingController!.clear();
                                  },
                                )
                              : null,
                        ),
                        cursorColor: const Color(0xFF00CEA8),
                        style: const TextStyle(fontSize: 12, color: Colors.black),
                        keyboardType: TextInputType.number,
                        obscureText: obscureTextToggle,
                        onChanged: (value) => setState(() {}),
                      ),
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    GestureDetector(
                      onTap: () {
                        setState(() {
                          obscureTextToggle = !obscureTextToggle;
                        });
                      },
                      child: obscureTextToggle
                          ? Image.asset(
                              'assets/yanjing_on.png',
                              width: 18,
                              height: 18,
                            )
                          : Image.asset(
                              'assets/yanjing.png',
                              width: 18,
                              height: 18,
                            ),
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 32, bottom: 12),
              child: TextButton(
                style: ButtonStyle(
                  overlayColor: WidgetStateProperty.all(Colors.transparent), // 移除水波纹效果
                ),
                onPressed: _handleRegister,
                child: Container(
                  alignment: Alignment.center,
                  width: double.infinity,
                  height: 50,
                  decoration: const BoxDecoration(
                      color: Color(0xFF00CEA8), borderRadius: BorderRadius.all(Radius.circular(10))),
                  child: const Text(
                    "完成",
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ),
              ),
            ),
            const Padding(
              padding: EdgeInsets.symmetric(horizontal: 12),
              child: Align(
                alignment: Alignment.centerRight,
                child: Text(
                  "需要幫助",
                  style: TextStyle(fontSize: 16, color: Color(0xFF00CEA8)),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}
